//
//  FirstVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/12/27.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "FirstVC.h"

#import "QLMHotNewsModel.h"
#import "QLMNewZhenjiTabCell.h"
#import "QLMHomeTableViewCell.h"

#import "TYCyclePagerView.h"
#import "TYPageControl.h"

#import "QLMHomepageCViewCell.h"
#import "QLMDetailAddressVC.h"
#import "QLMNoticeListVC.h"
#import "QLMAddBaoxiuVC.h"

#import "AppDelegate.h"
#import "homeData+CoreDataClass.h"
#import "QLMBXOrderDetailVC.h"

#import <SDImageCache.h>

@interface FirstVC ()<UITableViewDelegate,UITableViewDataSource,TextInfoViewDelegate,TYCyclePagerViewDataSource,TYCyclePagerViewDelegate,QLMNewZhenjiTabCellDelegate>{
    QLMHotNewsArrayModel *hotnewsArraymodel;
    NSArray *titleArray;
    NSArray *imagenameArray;
    NSArray *pjtitleArray;
    NSArray *pjimagenameArray;
    
    NSMutableArray *_annotitlearray;
    NSMutableArray *_annouUrlarray;
    
    float scaleNum;
    NSArray *idArray;
    __block NSString *networkStatusStr;
}
@property (nonatomic,strong)UITableView *hometableview;

@property (nonatomic,strong) TYCyclePagerView *pagerView;
@property (nonatomic,strong) TYPageControl *pageControl;
@property (nonatomic,strong) NSMutableArray *urlArray;

@end

@implementation FirstVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
    self.title=@"首页";
    
    idArray=[NSArray arrayWithObjects:@"1",@"2",@"4",@"15",@"16",nil];
    scaleNum = kScreen_width>375? 40:0;
    _urlArray = [NSMutableArray array];
    _annotitlearray=[NSMutableArray array];
    _annouUrlarray =[NSMutableArray array];

    titleArray=[NSArray arrayWithObjects:@"维修",@"保养",@"二手机",@"保险",@"学技能",nil];
    imagenameArray=[NSArray arrayWithObjects:@"01_weixiu",@"02_baoyang",@"03_ershouji",@"04_baoxian",@"05_banzheng", nil];
    pjtitleArray=[NSArray arrayWithObjects:@"保养包",@"液压件",@"发动机",@"底盘件",@"斗齿类", nil];
    pjimagenameArray=[NSArray arrayWithObjects:@"peijian_01",@"peijian_02",@"peijian_03",@"peijian_04",@"peijian_05", nil];
    
    hotnewsArraymodel=[[QLMHotNewsArrayModel alloc] init];
    hotnewsArraymodel.dataCarouselFigure=[NSArray array];
    hotnewsArraymodel.dataHotNews=[NSArray array];
    hotnewsArraymodel.dataAnnouncement=[NSMutableArray array];
    hotnewsArraymodel.dataAccessories=[NSArray array];
    
    CGRect rect=CGRectMake(0, 0, kScreen_width, kScreen_height-50);
    _hometableview=[[UITableView alloc] initWithFrame:rect style:UITableViewStyleGrouped];
    _hometableview.backgroundColor=[UIColor clearColor];
    _hometableview.delegate=self;
    _hometableview.dataSource=self;
    _hometableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    _hometableview.showsVerticalScrollIndicator=NO;
    _hometableview.showsHorizontalScrollIndicator=NO;
    _hometableview.tableFooterView=[UIView new];
    [self.view addSubview:_hometableview];
    
    if (@available(iOS 11.0, *)) {
        _hometableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    AppDelegate * app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *pushName = [[app.pushUserInfo objectForKey:@"aps"] objectForKey:@"alert"];
    if([ClientTool isNull:pushName]){
        [self getPushInfo:app.pushUserInfo];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self aFNetworkStatus];
    self.navigationController.navigationBarHidden=YES;
    [self requestHomeData];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 未启动app时，点击推送消息框 跳转界面
- (void)getPushInfo:(NSDictionary *)dict{
    if ([[UserManager sharedManager] isUserLogin]){//判断用户是否登录
        [self requRepairOrder:dict];
    }else{
        QLMLoginViewController *loginController = [QLMLoginViewController new];
        loginController.pushUid=dict[@"userId"];
        loginController.resultBlock=^(BOOL success){};
        QLMCustomNavCtr *nav=[[QLMCustomNavCtr alloc] initWithRootViewController:loginController];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    }
}

- (void)requRepairOrder:(NSDictionary *)dict{
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:dict[@"repairOrderId"] forKey:@"repairOrderId"];
    [ClientTool postUrlPath:@"/test/repairOrder/orderInfo" withParamers:paramerDic andBody:nil
                    success:^(id responseObject){
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            QLMOrderListInfoModel *resultInfoModel=[[QLMOrderListInfoModel alloc] initWithDictionary:responseObject[@"repairOrder"] error:nil];
                            [self pushToOrderDetailVC:resultInfoModel withOrderId:dict[@"repairOrderId"]];
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)pushToOrderDetailVC:(QLMOrderListInfoModel *)resultOrderModel withOrderId:(NSString *)orderId{
    QLMBXOrderDetailVC *messageVC = [QLMBXOrderDetailVC new];
    messageVC.repairOrderId=orderId;
    messageVC.resultInfoModel=resultOrderModel;
    messageVC.isPushJumpBool=YES;
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:messageVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

#pragma mark - 插入数据
- (void)addIntoDataSource:(NSArray *)ajsonArray{
    AppDelegate *_myAppDelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    homeData *user=(homeData *)[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:_myAppDelegate.managedObjectContext];
    [user setHomeInfo:ajsonArray];
    
    NSError *error;
    BOOL isSaveSuccess=[_myAppDelegate.managedObjectContext save:&error];
    if (!isSaveSuccess) {
        NSLog(@"Error:%@",error);
    }else{
        NSLog(@"Save successful!");
    }
}

//查询
- (NSDictionary *)query{
    NSDictionary *ajsonDic=[NSDictionary dictionary];
    AppDelegate *_myAppDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    NSFetchRequest *request=[[NSFetchRequest alloc] init];
    NSEntityDescription * user=[NSEntityDescription entityForName:@"Entity" inManagedObjectContext:_myAppDelegate.managedObjectContext];
    [request setEntity:user];
    
    NSError *error=nil;
    NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResult==nil) {
        NSLog(@"Error:%@",error);
    }
    if ([mutableFetchResult count]!=0) {
        homeData *user=[mutableFetchResult objectAtIndex:0];
        NSArray *ajsonArray=(NSArray *)user.homeInfo;
        ajsonDic=ajsonArray[0];
    }
    return ajsonDic;
}

#pragma mark - request HomeData
- (void)requestHomeData{
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/homePage/getAll" withParamers:nil andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1){
                            NSDictionary *dic=responseObject[@"data"];
                            [self updateDataModel:dic];
                            [self addIntoDataSource:[NSArray arrayWithObject:dic]];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

#pragma mark - aFNetworkStatus
- (void)aFNetworkStatus{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSString *statusInt=nil;
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                statusInt=@"1";
                break;
            case AFNetworkReachabilityStatusNotReachable:
                statusInt=@"2";
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                statusInt=@"3";
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                statusInt=@"4";
                break;
            default:
                break;
        }
        
        networkStatusStr=statusInt;
        if ([statusInt integerValue]==2) {
            [self updateDataModel:[self query]];
        }
    }];
    [manager startMonitoring];
}

- (void)updateDataModel:(NSDictionary *)dic{
    
    [_annotitlearray removeAllObjects];
    [_annouUrlarray removeAllObjects];
    [_urlArray removeAllObjects];
    
    hotnewsArraymodel.dataCarouselFigure=dic[@"dataCarouselFigure"];
    hotnewsArraymodel.dataHotNews=dic[@"dataHotNews"];
    hotnewsArraymodel.dataAnnouncement=[NSMutableArray arrayWithArray:dic[@"dataAnnouncement"]];
    hotnewsArraymodel.dataAccessories=dic[@"dataAccessories"];
    
    for (int i=0; i<hotnewsArraymodel.dataAnnouncement.count; i++) {
        QLMAnnouncementModel *announceModel=[[QLMAnnouncementModel alloc] initWithDictionary:hotnewsArraymodel.dataAnnouncement[i] error:nil];
        [_annotitlearray addObject:announceModel.announcementTitle];
        [_annouUrlarray addObject:announceModel.announcementId];
    }
    
    for (int i=0; i<hotnewsArraymodel.dataCarouselFigure.count; i++) {
        QLMCarouselFigureModel *carouseModel=[[QLMCarouselFigureModel alloc] initWithDictionary:hotnewsArraymodel.dataCarouselFigure[i] error:nil];
        [_urlArray addObject:carouseModel.pictureUrl];
    }
    
    [_hometableview reloadData];
}

#pragma mark -
- (UIButton *)acreatButton:(CGRect)aFrame title:(NSString *)aTitle image:(NSString *)imageName{
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.frame = aFrame;
    [newButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [newButton setTitle:aTitle forState:UIControlStateNormal];
    [newButton setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    newButton.backgroundColor = [UIColor whiteColor];
    newButton.titleLabel.font=[UIFont systemFontOfSize:16.0f];
    [newButton addTarget:self action:@selector(newButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    return newButton;
}

- (NSString *)timeWithTimeIntervalString:(NSString *)timeString{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}

#pragma mark - 轮播图
- (void)addPagerView:(UIView *)header{
    TYCyclePagerView *pagerView = [[TYCyclePagerView alloc]init];
    pagerView.frame = CGRectMake(0, 0, kScreen_width, 180+scaleNum);
    pagerView.isInfiniteLoop = YES;
    pagerView.autoScrollInterval = 3.0;
    pagerView.dataSource = self;
    pagerView.delegate = self;
    [pagerView registerClass:[QLMHomepageCViewCell class] forCellWithReuseIdentifier:@"pagecellId"];
    [header addSubview:pagerView];
    
    _pagerView = pagerView;
}

- (void)addPageControl {
    
    TYPageControl *pageControl = [[TYPageControl alloc]init];
    pageControl.frame = CGRectMake(0, CGRectGetHeight(_pagerView.frame) - 26, CGRectGetWidth(_pagerView.frame), 26);
    pageControl.currentPageIndicatorSize = CGSizeMake(8, 8);
    [_pagerView addSubview:pageControl];
    
    _pageControl = pageControl;
    _pageControl.numberOfPages = _urlArray.count;
    [_pagerView reloadData];
}

#pragma mark - TYCyclePagerViewDataSource
- (NSInteger)numberOfItemsInPagerView:(TYCyclePagerView *)pageView {
    return _urlArray.count;
}

- (UICollectionViewCell *)pagerView:(TYCyclePagerView *)pagerView cellForItemAtIndex:(NSInteger)index {
    
    QLMHomepageCViewCell *cell = [pagerView dequeueReusableCellWithReuseIdentifier:@"pagecellId" forIndex:index];
    NSString *picUrlStr=[NSString stringWithFormat:@"%@%@",kBaseURL,_urlArray[index]];
    
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    if ([networkStatusStr integerValue]==2) {
        // 从缓存取图片并显示
        UIImage *image = [manager.imageCache imageFromCacheForKey:picUrlStr];
        cell.pageImageview.image=image;
    }else{
        [cell.pageImageview sd_setImageWithURL:[NSURL URLWithString:picUrlStr] placeholderImage:[UIImage imageNamed:@"default_bg"]];
        // 缓存图片
        [manager.imageDownloader downloadImageWithURL:[NSURL URLWithString:picUrlStr] options:SDWebImageDownloaderContinueInBackground progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {

        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
//            NSLog(@"---save image is %i",finished);
            [manager.imageCache storeImage:image forKey:picUrlStr toDisk:YES completion:nil];
        }];
    }
    
    return cell;
}

- (TYCyclePagerViewLayout *)layoutForPagerView:(TYCyclePagerView *)pageView {
    TYCyclePagerViewLayout *layout = [[TYCyclePagerViewLayout alloc]init];
    layout.itemSize = CGSizeMake(CGRectGetWidth(pageView.frame), CGRectGetHeight(pageView.frame));
    layout.itemSpacing = 0;
    layout.itemHorizontalCenter = YES;
    return layout;
}

- (void)pagerView:(TYCyclePagerView *)pageView didScrollFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    _pageControl.currentPage = toIndex;
}

- (void)pagerView:(TYCyclePagerView *)pageView didSelectedItemCell:(__kindof UICollectionViewCell *)cell atIndex:(NSInteger)index{
    
    QLMCarouselFigureModel *carouseModel=[[QLMCarouselFigureModel alloc] initWithDictionary:hotnewsArraymodel.dataCarouselFigure[index] error:nil];
    NSString *htmlStr=nil;
    if([carouseModel.skipUrl hasPrefix:@"http://"]||[carouseModel.skipUrl hasPrefix:@"https://"]){
        htmlStr=carouseModel.skipUrl;
    }else{
        htmlStr=[NSString stringWithFormat:@"http://%@",carouseModel.skipUrl];
    }
    [self pushToWebviewWithHtmlUrl:htmlStr andTitle:@""];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - UITableView datasource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 180+scaleNum;
    }
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView=[[UIView alloc] init];
    headerView.backgroundColor=[UIColor clearColor];
    
    if (section==0){
        UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 180+scaleNum)];
        imageView.backgroundColor=[UIColor whiteColor];
        [headerView addSubview:imageView];
        
        [self addPagerView:headerView];
        [self addPageControl];
    }else{
        UIView *backView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 44)];
        backView.backgroundColor=[UIColor whiteColor];
        [headerView addSubview:backView];
        
        UIView *lineView=[[UIView alloc] initWithFrame:CGRectMake(0, 44-0.2, kScreen_width, 0.2)];
        lineView.backgroundColor=[UIColor lightGrayColor];
        [headerView addSubview:lineView];
    
        NSString *btnTitle=@"新闻";
        if (section==3) {
            btnTitle=@"配件";
        }else if (section==2){
            btnTitle=@"整机";
        }
        
        CGRect leftButtonRect=CGRectMake(15, 10, 80, 24);
        UIButton *newsButton=[self acreatButton:leftButtonRect title:btnTitle image:@"icon"];
        newsButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        newsButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        newsButton.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
        newsButton.titleLabel.font=[UIFont systemFontOfSize:16.0f];
        [headerView addSubview:newsButton];
        
        if (section==1) {
            CGRect rightButtonRect=CGRectMake(kScreen_width-60-20, 10, 60, 24);
            UIButton *rightButton=[self acreatButton:rightButtonRect title:[NSString stringWithFormat:@"查看更多"] image:@"next"];
            rightButton.tag=2001;
            [rightButton setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
            rightButton.titleLabel.font=[UIFont systemFontOfSize:16.0f];
            rightButton.imageEdgeInsets = UIEdgeInsetsMake(0, rightButton.frame.size.width - rightButton.imageView.frame.size.width, 0, 0);
            rightButton.titleEdgeInsets = UIEdgeInsetsMake(0, 35-(rightButton.frame.size.width - rightButton.imageView.frame.size.width ), 0, 0);
            [headerView addSubview:rightButton];
        }
    }
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==3) {
        return 0.1;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView=[[UIView alloc] init];
    footerView.backgroundColor=[UIColor clearColor];
    return footerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0||section==1) {
        return 2;
    }
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if (indexPath.row==1) {
            return 60;
        }
        return 80;
    }else if(indexPath.section==1){
        return 67;
    }else if (indexPath.section==2){
        return 120;
    }
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        QLMHomeTableViewCell *homecell=[QLMHomeTableViewCell cellWithTableView:tableView];
        homecell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        if (hotnewsArraymodel.dataHotNews.count!=0) {
            QLMHotNewsModel *hotnewsModel=[[QLMHotNewsModel alloc] initWithDictionary:hotnewsArraymodel.dataHotNews[indexPath.row] error:nil];
            
            homecell.detailNewsLabel.font=[UIFont systemFontOfSize:18.0f];
            homecell.detailNewsLabel.text=hotnewsModel.newsTitle;
            homecell.timeLabel.text = [self timeWithTimeIntervalString:hotnewsModel.newsPubdate];
            homecell.timeLabel.font=[UIFont systemFontOfSize:16.0f];
            [homecell.iconImageview sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseURL,hotnewsModel.newsPicturePath]] placeholderImage:[UIImage imageNamed:@"img_news"]];
        }
        
        return homecell;
    }
    
    if (indexPath.section==0||indexPath.section==3){
        
        static NSString *cellid=[NSString stringWithFormat:@"homecellid%ld%ld",(long)indexPath.section,(long)indexPath.row];
        UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
        if (cell==nil) {
            cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
        
        if (indexPath.section==0) {
            
            if (indexPath.row==0) {
                for (int i=0; i<5; i++) {
                    CGRect rectButton=CGRectMake(2+((kScreen_width-12)/5+2)*i, 10, (kScreen_width-12)/5, 60);
                    UIButton *pushButton=[self acreatButton:rectButton title:titleArray[i] image:imagenameArray[i]];
                    [pushButton verticalImageAndTitle:5];
                    [pushButton setTitleColor:UIColorFromRGB(0x000000) forState:UIControlStateNormal];
                    pushButton.titleLabel.font=[UIFont systemFontOfSize:18];
                    pushButton.tag=1000+i;
                    [cell addSubview:pushButton];
                }
            }else{
                
                UIButton *iconBtn=[self acreatButton:CGRectMake(20, 16, 28, 28) title:nil image:@"notice"];
                iconBtn.tag=3001;
                iconBtn.backgroundColor=[UIColor clearColor];
                [cell addSubview:iconBtn];
                
                if (_annotitlearray.count!=0) {
                    [self createVLabelUI:cell withModelArray:_annotitlearray andIdArray:_annouUrlarray];
                }
            }
            
        }else if (indexPath.section==3){
            
            for (int i=0; i<5; i++) {
                CGRect rectButton=CGRectMake(2+((kScreen_width-12)/5+2)*i, 10, (kScreen_width-12)/5, 60);
                UIButton *pushButton=[self acreatButton:rectButton title:pjtitleArray[i] image:pjimagenameArray[i]];
                [pushButton verticalImageAndTitle:-5];
                pushButton.tag=1005+i;
                pushButton.titleLabel.font=[UIFont systemFontOfSize:18];
                [cell addSubview:pushButton];
            }
        }
        
        return cell;
    }
    
    QLMNewZhenjiTabCell *zhenjicell=[QLMNewZhenjiTabCell cellWithTableView:tableView];
    zhenjicell.delegate=self;
    return zhenjicell;
}

#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section==1) {
        QLMHotNewsModel *hotnewsModel=[[QLMHotNewsModel alloc] initWithDictionary:hotnewsArraymodel.dataHotNews[indexPath.row] error:nil];
        NSString *htmlStr=nil;
        if ([hotnewsModel.newsPath length]==0) {
            htmlStr=[NSString stringWithFormat:@"%@/html/phone/newsDetails.html?id=%@",kBaseURL,hotnewsModel.hotNewsId];
        }else{
            htmlStr=hotnewsModel.newsPath;
        }
        [self pushToWebviewWithHtmlUrl:htmlStr andTitle:@"新闻"];
    }
}

#pragma mark - delegate
- (void)didselectItem:(NSInteger)selectItemInt{//整机
    NSString *tmpUserid=[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:kLoginUserId]];
    NSString *userId=nil;
    if (tmpUserid.length==0) {
        userId=@"";
    }else{
        userId=tmpUserid;
    }
    
    NSString *htmlurlStr=nil;
    NSString *title=nil;
    if (selectItemInt==5460) {
        htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/machine.html?id=%@&userId=%@",kBaseURL,@"-3",userId];
        title=@"土石方机械";
    }else if (selectItemInt==5461){
        htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/machine.html?id=%@&userId=%@",kBaseURL,@"-4",userId];
        title=@"路面机械";
    }else if (selectItemInt==5462){
        htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/assemblyMachine.html?typeId=%@&userId=%@",kBaseURL,@"-5",userId];
        title=@"再制造机械";
    }
    [self pushToWebviewWithHtmlUrl:htmlurlStr andTitle:title];
}

- (void)newButtonAction:(UIButton *)sender{//报修 1000~1004  配件 1005~1009
    if (sender.tag==3001) {//点击小马公告图标
        QLMNoticeListVC *noticeListVC=[QLMNoticeListVC new];
        noticeListVC.arrayModel=hotnewsArraymodel;
        self.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:noticeListVC animated:YES];
        self.hidesBottomBarWhenPushed=NO;
    }else if(sender.tag==2001){//新闻查看更多
        NSString *htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/news.html",kBaseURL];
        NSString *title=@"新闻";
        [self pushToWebviewWithHtmlUrl:htmlurlStr andTitle:title];
    }else{
        NSString *htmlurlStr=nil;
        NSString *title=nil;
        if (sender.tag==1000||sender.tag==1001) {
    
            if ([[UserManager sharedManager] isUserLogin]) {//判断是否登录
                if (sender.tag==1001){
                    [self pushToBaoxiuVC:YES];
                }else{
                    [self pushToBaoxiuVC:NO];
                }
            }else{
                [self presentaLoginVC];
            }
            
        }else if (sender.tag==1002) {
            htmlurlStr=@"http://ershouji.sevalo.com/ershouji/index.aspx";
            title=@"二手机";
            [self pushToWebviewWithHtmlUrl:htmlurlStr andTitle:title];
        }else if (sender.tag==1003) {
            htmlurlStr=@"http://beta.sevalo.com/exiaoma_wx/insurancePage/insurance.html";
            title=@"保险";
            [self pushToWebviewWithHtmlUrl:htmlurlStr andTitle:title];
        }else if (sender.tag==1004){
            htmlurlStr=@"http://www.haojishou.cn/";
            title=@"学技能";
            [self pushToWebviewWithHtmlUrl:htmlurlStr andTitle:title];
        }else{
            if (sender.tag>1004) {
                NSString *tmpUserid=[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:kLoginUserId]];
                NSString *userId=nil;
                if (tmpUserid.length==0) {
                    userId=@"";
                }else{
                    userId=tmpUserid;
                }
                
                NSString *accessoriesStr=@"/html/phone/accessories.html?typeId=";
                htmlurlStr=[NSString stringWithFormat:@"%@%@%@&userId=%@",kBaseURL,accessoriesStr,idArray[sender.tag-1005],userId];
                title=@"配件展示";
                [self pushToWebviewWithHtmlUrl:htmlurlStr andTitle:title];
            }
        }
        
    }
}

- (void)pushToWebviewWithHtmlUrl:(NSString *)htmlUrlStr andTitle:(NSString *)title{
    QLMDetailAddressVC *webVC=[QLMDetailAddressVC new];
    webVC.htmlurlStr=htmlUrlStr;
    webVC.title=title;
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:webVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)pushToBaoxiuVC:(BOOL)isCanEdit{
    QLMAddBaoxiuVC *bxOrderDetailVC=[QLMAddBaoxiuVC new];
    bxOrderDetailVC.isBaoyangDevicebool=isCanEdit;
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:bxOrderDetailVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)presentaLoginVC{
    QLMLoginViewController *loginController = [QLMLoginViewController new];
    loginController.resultBlock=^(BOOL success){};
    QLMCustomNavCtr *nav=[[QLMCustomNavCtr alloc] initWithRootViewController:loginController];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

#pragma mark - TextInfoViewDelegate
- (void)handleTopEventWithURLString:(NSString *)URLString{
    NSString *htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/announcementDetails.html?id=%@",kBaseURL,URLString];
    NSString *title=@"小马公告";
    [self pushToWebviewWithHtmlUrl:htmlurlStr andTitle:title];
}

- (void)handleBottomEventWithURLString:(NSString *)URLString{
    NSString *htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/announcementDetails.html?id=%@",kBaseURL,URLString];
    NSString *title=@"小马公告";
    [self pushToWebviewWithHtmlUrl:htmlurlStr andTitle:title];
}

- (void)getBottomDataSourceModel:(DataSourceModel *)bottomDataSourceModel{
    
}

- (void)getTopDataSourceModel:(DataSourceModel *)topDataSourceModel{
    
}

- (void)createVLabelUI:(UITableViewCell *)headerView withModelArray:(NSMutableArray *)modelArray andIdArray:(NSMutableArray *)idArray{
    
    XLsn0wTextCarousel *view=[[XLsn0wTextCarousel alloc] initWithFrame:CGRectMake(50,10,kScreen_width-50-10, 40)];
    view.currentTextInfoView.xlsn0wDelegate = self;
    view.hiddenTextInfoView.xlsn0wDelegate = self;
    view.backgroundColor =[UIColor whiteColor];
    [headerView addSubview:view];
    
    NSMutableArray *_dataSourceArray = [NSMutableArray array];
    for (int i = 0; i < modelArray.count; i++) {
        
        NSString *title = [modelArray objectAtIndex:i];
        NSString *URLString = [idArray objectAtIndex:i];
        
        DataSourceModel *model = [DataSourceModel dataSourceModelWithType:nil title:title URLString:URLString];
        [_dataSourceArray addObject:model];
    }
    view.dataSourceArray = _dataSourceArray;
}

@end
